<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\Model\Category;

use App\Model\HotelReferral;
use JWTAuth;
use DB;

class CategoryApiController extends Controller
{

    public function __construct()
    {
        parent::__construct();
        view()->share([
            '_xApi' => 'am-in',
        ]);
    }

    public function api_list(){
        return Category::all();
    }


    function getCategoryList()
    {

        $data = array();
        $category = Category::select('id', 'name')->with(['children_api' => function ($query) {
            $query->select('name', 'parent_id');
        }])->where(['parent_id' => 0])->orderBy('id','desc')->get();

        if ($category->isEmpty()) {
            $data['info'] = '获取数据失败';
            $data['status'] = false;
            return $data;
        }

        $data['status'] = true;
        $data['info'] = '成功获取信息';

        foreach ($category->toArray() as $key => $value) {
            $result[] = $value;
            $result[$key]['children_name'] = array_column($value['children_api'], 'name');
            if(empty($result[$key]['children_name'])){
                unset($result[$key]);
            }
            unset($result[$key]['children_api']);
        }

        $data['data'] = $result;
        return $data;

    }

    function getHotelreferralList()
    {

        $data = array();
        $hotelReferral = HotelReferral::with(['gallery' => function ($query) {
            $query->select('img', 'hotel_referral_id');
        }])->with(['category' => function ($query) {
            $query->select('id', 'name');
        }])->select('id', 'category_id', 'desc')->where('is_show', true)->get();


        if ($hotelReferral->isEmpty()) {
            $data['info'] = '获取数据失败';
            $data['status'] = false;
            return $data;
        }

        $data['status'] = true;
        $data['info'] = '成功获取详情';
        
        foreach ($hotelReferral->toArray() as $key => $value) {
            $result[] = $value;
            $result[$key]['children_name'] = array_column($value['gallery'], 'img');
            unset($result[$key]['gallery']);
            $result[$key]['name'] = $value['category']['name'];
            unset($result[$key]['category']);
            unset($result[$key]['category_id']);
        }
        $data['data'] = $result;
        return $data;

    }


}
